import { IObject, useRefCallback } from '@newgrand/iup-core';
import { Tooltip } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { Select } from '../../../baseComponent';
import { iup } from '../../../util';
import { saveAttachLabel } from '../service';

type LabelSelectProps = {
  labelConfig: IObject;
  fileId: string;
  onChangeCallback?: Function;
};

const defaultWidth = 150;
export function LabelSelect(props: LabelSelectProps) {
  const { labelConfig, fileId, onChangeCallback } = props;
  const { options, multiple, style, defaultValue, disabled, value: propsValue, ...others } = labelConfig;
  const [open, setOpen] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [value, setValue] = useState<string[]>([]);

  const preValue = useMemo(() => {
    const v = propsValue || defaultValue;
    return Array.isArray(v) ? v : [v];
  }, [propsValue, defaultValue]);

  useEffect(() => {
    setValue(preValue);
  }, [preValue]);

  const handleLabelChange = useRefCallback((label: string[]) => {
    setUpdating(true);
    const params = {
      fileId,
      label
    };
    saveAttachLabel(params)
      .then((res) => {
        if (res?.code === 0) {
          onChangeCallback && onChangeCallback();
        } else {
          setValue(defaultValue);
        }
      })
      .finally(() => {
        setUpdating(false);
      });
  });

  const newProps: IObject = {
    options,
    multiple: !!multiple,
    disabled,
    style: { width: defaultWidth, maxHeight: '100%', ...style },
    ...others
  };
  if (newProps.multiple) {
    newProps.maxTagCount = newProps.hasOwnProperty('maxTagCount') ? newProps.maxTagCount : 'responsive';
    newProps.maxTagPlaceholder = (omittedValues) => {
      const len = omittedValues?.length;
      if (len) {
        const tipTitle = (
          <div
            style={{ padding: '6px 8px', wordBreak: 'break-all', whiteSpace: 'normal' }}
            onClick={(e) => e.stopPropagation()}
            onMouseDown={(e) => e.stopPropagation()}
          >
            {omittedValues.map((v) => v.label).join(', ')}
          </div>
        );
        return (
          <Tooltip overlayInnerStyle={{ padding: 0 }} title={tipTitle} mouseEnterDelay={0.2}>
            <span style={{ display: 'inline-flex', alignItems: 'center', maxWidth: '100%' }}>
              <span className="nowrap" style={{ flex: 1 }}>
                {omittedValues[0].label}
              </span>
              {len > 1 ? `,  + ${len - 1} ...` : ``}
            </span>
          </Tooltip>
        );
      }
      return null;
    };
  }
  return (
    <Select
      {...newProps}
      open={open}
      loading={newProps.loading || updating}
      value={value}
      onDropdownVisibleChange={(_open) => {
        setOpen(_open);
        if (!_open && preValue.join('') !== value.join('')) {
          handleLabelChange(value);
        }
      }}
      onChange={(v) => {
        const values = iup.isArray(value) ? v.map((op) => op.value) : [v.value];
        if (!open) {
          handleLabelChange(values);
        }
        setValue(values);
      }}
    />
  );
}
